<template>
  <el-table ref="multipleTableRef" :data="tableData" @selection-change="handleSelectionChange" row-key="id" style="width: 100%" height="500px">
      <el-table-column type="selection" width="55" />
      <el-table-column property="account" label="账号" width="200" />
      <el-table-column property="userGroup" label="用户组" width="450" />
      <el-table-column label="创建时间" width="200">
          <template #default="scope">{{ formatDate(scope.row.ctime) }}</template>
      </el-table-column>
      <el-table-column width="400" label="操作">
          <template #default="scope">
              <el-button size="small" style="background-color: lightskyblue; color: white;"
                         @click="handleEdit(scope.$index, scope.row)">
                  编辑
              </el-button>
              <el-button size="small" type="danger" @click="open(scope.$index, scope.row)">
                  删除
              </el-button>
          </template>
      </el-table-column>
  </el-table>
  <!-- 新增批量删除按钮 -->
  <el-button type="danger" @click="batchDeleteBtn">批量删除</el-button>
  <!-- 修改信息 -->
  <el-dialog v-model="dialogFormVisible" title="修改账号信息" width="500">
      <el-form :model="form">
          <el-form-item label="账号名" :label-width="formLabelWidth">
              <el-input v-model="form.name" :placeholder="form.name" autocomplete="off" />
          </el-form-item>
          <el-form-item label="用户组" :label-width="formLabelWidth">
              <el-select v-model="form.region" :placeholder="form.region">
                  <el-option label="超级管理员" value="超级管理员" />
                  <el-option label="普通管理员" value="普通管理员" />
              </el-select>
          </el-form-item>
      </el-form>
      <template #footer>
          <div class="dialog-footer">
              <el-button @click="dialogFormVisible = false">取消</el-button>
              <el-button type="primary" @click="handleSave">
                  确定
              </el-button>
          </div>
      </template>
  </el-dialog>
  <div style="margin-top: 20px">
      <Pagination :total="total" @pageChange="handlePageChange" />
  </div>
</template>
<script lang="ts" setup>
import { onMounted, ref } from 'vue';
import { getaccount } from '../api/account';
import { reactive } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import Pagination from './Pagination.vue';
import { delaccount ,batchdel,del} from '../api/account';
import { reviseaccount } from '../api/account';
import dayjs from 'dayjs';

const multipleTableRef = ref(null); // 用于获取表格实例
const dialogFormVisible = ref(false);
const formLabelWidth = '140px';
const selectedIds = ref([]);
const form = reactive({
  name: '',
  region: '',
  date1: '',
  date2: '',
  delivery: false,
  type: [],
  resource: '',
  desc: '',
});
//更新数据


const total = ref(0); // 总条目数

let currentEditIndex = -1;

// 格式化时间
const formatDate = (date: string) => {
  return dayjs(date).format('YYYY-MM-DD HH:mm:ss'); // 使用 dayjs 格式化时间
};

interface User {
  account: string;
  ctime: string;
  id: string | number;
  userGroup: string;
  imgUrl: string;
}

const tableData = ref<User[]>([]);
const params = ref({
  currentPage: 1,
  pageSize: 5,
});

// 获取用户列表
const getdata = async (msg) => {
  const data = await getaccount(msg);
  console.log(data);
  tableData.value = data.data; // 假设返回的数据结构包含 records 和 total
  total.value = data.total; // 更新总条目数
};

// 删除用户（单个删除）
const handleDelete = async(id) => {
    const res = await del({id: id});
    console.log(res);
    if(res.code === 0){
      ElMessage.success("删除成功");
    } else {
      ElMessage.error("删除失败");
    }
 
}

// 修改用户
const handleUpdate = async (userdata) => {
  const { msg,code } = await reviseaccount(userdata);
  if(code === 0){
    ElMessage.success(msg);
  }
};

onMounted(() => {
  getdata(params.value);
});

// 编辑
const handleEdit = (index: number, row: User) => {
  dialogFormVisible.value = true;
  currentEditIndex = index;
  form.name = row.account;
  form.region = row.userGroup;
};

// 编辑点击确定
const handleSave = () => {
  if (currentEditIndex !== -1) {
    const row = tableData.value[currentEditIndex];
    tableData.value[currentEditIndex].account = form.name;
    tableData.value[currentEditIndex].userGroup = form.region;
    const data = {
      id: row.id,
      account: form.name, // 使用修改后的账号名
      userGroup: form.region, // 使用修改后的用户组
    };
    handleUpdate(data);
  }
  dialogFormVisible.value = false; // 确保在操作完成后关闭对话框
};

// 删除
const open = (index: number, row: User) => {
  ElMessageBox.confirm(
    '此操作将永久删除该用户，是否继续？',
    '警告',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      // 从表格数据中删除当前行
      tableData.value.splice(index, 1);
      handleDelete(row.id);
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '已取消删除',
      });
    });
};

// 新增：处理表格选择变化
const handleSelectionChange = (selection) => {
  selectedIds.value = selection.map(item => item.id);
}

// 新增：批量删除方法
const batchDeleteBtn = async() => {
  if (selectedIds.value.length === 0) {
    ElMessage.warning('请至少选择一条数据');
    return;
  }

    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedIds.value.length} 条账号吗？`, 
      '提示', 
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    );
    
    const res = await batchdel(selectedIds.value);
    console.log(res);
    
    if(res.code === 0){
      ElMessage.success("批量删除成功");
      getdata(params.value); // 刷新列表
      selectedIds.value = []; // 清空选择
    } else {
      ElMessage.error("批量删除失败");
    }
}


const handlePageChange = (data: { currentPage: number; pageSize: number }) => {
  params.value.currentPage = data.currentPage;
  params.value.pageSize = data.pageSize;
  getdata(params.value);
};
</script>
